//
//  EventEditMemberController.m
//  whopaidforit
//
//  Created by Hoang Vu on 1/26/13.
//  Copyright (c) 2013 Hoang Vu. All rights reserved.
//

#import "EventEditMemberController.h"

@interface EventEditMemberController ()

@end

@implementation EventEditMemberController

@synthesize viewAdd, txtTitle, lblPrice, scrollView, btCancel, btDelete;

@synthesize listData, arrCheckbox,keyArray, listNew;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    listData = [[NSMutableArray alloc] init];
    //listNew =
    arrCheckbox = [[NSMutableArray alloc] init];
    [self loadData];
    [self createNavigation];
    [self changeStyle];
    [self showGripUser];
}
-(void) changeStyle
{
    [StyleControl background:self.view];
    [StyleControl setViewStyle:viewAdd];
    [StyleControl drawLine:self.viewAdd PositionX:0 PositionY:45 Width:306];
    [StyleControl drawLine:self.viewAdd PositionX:0 PositionY:90 Width:306];
    UIImageView *image = [[UIImageView alloc] init];
    image.frame = CGRectMake(4,7, 30,26);
    [image setImage:[UIImage imageNamed:@"event"]];
    [viewAdd addSubview:image];
    [image release];
    btCancel.layer.cornerRadius = 5;
    btDelete.layer.cornerRadius = 5;
    btCancel.layer.masksToBounds = YES;
    btDelete.layer.masksToBounds = YES;
    [StyleControl setPriceStyle:lblPrice];
}
-(void) createNavigation
{
    UIButton *left =[UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *right =[UIButton buttonWithType:UIButtonTypeCustom];
    [left setImage:[UIImage imageNamed:@"buttonlist"] forState:UIControlStateNormal];
    left.frame = CGRectMake(8, 8, 37, 35);
    right.frame = CGRectMake(250, 8, 60, 35);
    [right setTitle:@"Gereed" forState:UIControlStateNormal];
    NSString *title = [NSString stringWithFormat:NSLocalizedString(@"event.edit.member", @"")];
    [left addTarget:self action:@selector(openEventList) forControlEvents:UIControlEventTouchUpInside];
    [right addTarget:self action:@selector(saveEvent) forControlEvents:UIControlEventTouchUpInside];
    [StyleControl naviStyle:self.view andTitle:title andColor:0 andleftButton:left andRightButton:right borderLeft:1 borderRight:1];
}
-(void) loadData
{
    Event *event = [Event instance];
    NSMutableArray *datas = [event getListMember:event._id];
    EventClass *eventClass = [datas objectAtIndex:0];
    txtTitle.text = eventClass.eventTitle;
    lblPrice.text = [StyleControl formatCurrency:[NSString stringWithFormat:@"%.2f",eventClass.totalAmount] addCurency:YES];
    listData = [datas objectAtIndex:1];
    if([listNew count]){
        for (int i=0; i<[listNew count]; i++) {
            [listData addObject:[listNew objectAtIndex:i]];
        }
    }
}

-(void)showGripUser
{
    //[scrollView setBackgroundColor:[UIColor blueColor]];
    //scroll view
    for(UIView *subview in [self.scrollView subviews]) {
        [subview removeFromSuperview];
        //NSLog(@"Subviews Count=%d",myScrollView.subviews.count);
    }
    //number items per row
    int a=4;
    //number items per column
    int b=2;
    if([listData count] < 7) b = 2;
    //total items + 1 for add item in last
    int c=[self.listData count]+1;
    //c += [self.listNew count];
    //width of scrollView
    int d=scrollView.frame.size.width;
    //height of scrollView
    int d2=scrollView.frame.size.height;
    //width of an item
    int e=d/a;
    //height of an item
    int f=d2/b-15;
    int i=0;
    int numPages = ceil(1.0f*c/(a*b));
    for (int p=0; p<numPages; p++) {
        for (int m=0; m<b; m++) {
            for (int n=0; n<a && i<c; n++) {
                UIView *itemView = [[UIView alloc] initWithFrame:CGRectMake(((p*d)+(n*e)), (m*f), e, f-16)];
                if(i == c-1){
                    UIButton *addMemberButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    addMemberButton.frame = CGRectMake(10, 10, 50, 50);
                    [addMemberButton setImage:[UIImage imageNamed:@"addmember"] forState:UIControlStateNormal];
                    [addMemberButton addTarget:self action:@selector(showAddMember) forControlEvents:UIControlEventTouchUpInside];
                    [addMemberButton setTitle:@"Lid toevoegen" forState:UIControlStateNormal];
                    [itemView addSubview:addMemberButton];
                }else{
                    if(i >= [listData count]){
                        ParticipateClass  *par = [self.listNew objectAtIndex:(i-[listData count])];
                        UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
                        im.image = [Helper getImageMember:par];
                        [StyleControl setBorderStyle:im];
                        [itemView addSubview:im];
                        [im release];
                    }else{
                        ParticipateClass  *par = [self.listData objectAtIndex:i];
                        UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
                        im.image = [Helper getImageMember:par];
                        [StyleControl setBorderStyle:im];
                        [itemView addSubview:im];
                        [im release];
                    }
                    
                    
                    UIButton *bt = [[UIButton alloc] init];
                    bt.frame = CGRectMake(26, 65, 18, 18);
                    [bt.layer setMasksToBounds:YES];
                    bt.layer.borderColor = [UIColor colorWithRed:0.278 green:0.275 blue:0.275 alpha:1.0].CGColor;
                    bt.layer.borderWidth = 1.0f;
                    bt.layer.cornerRadius = 10;
                    
                    //[itemView addSubview:bt];
                    [bt release];
                    
                    LocationClass *location = [[LocationClass alloc] init];
                    location.xLocation = (p*d)+(n*e) + 25;
                    location.yLocation = (m*f) + f - 34;
                    [arrCheckbox addObject:location];
                    [location release];
                }
                
                [scrollView addSubview:itemView];
                [itemView release];
                i++;
            }
        }
    }
    scrollView.contentSize = CGSizeMake(d*(numPages), d2);
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    
    CheckBox *check = [[CheckBox alloc] init];
    check.delegate = self;
    [check drawCheckBox:self.scrollView andLocation:arrCheckbox];
}
-(void)checkBoxReply:(NSInteger)index andCount:(NSInteger)count
{
    NSString *title = [NSString stringWithFormat:@"Verwijder (%d)", count];
    [btDelete setTitle:title forState:UIControlStateNormal];
}
-(void)keylistCheck:(NSMutableDictionary *)keyList
{
    keyArray = [[NSMutableDictionary alloc] init];
    keyArray = keyList;
}
-(void) openEventList
{
    BookingListController *detail = [[BookingListController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(void) saveEvent
{
    Event *event = [Event instance];
    User *user = [User instance];
    [event updateEventWS:event._id userId:user._id Name:txtTitle.text Description:@""];
    event._name = txtTitle.text;
    
    // save all member in that event
    Participate *par = [Participate instance];
    [par addForEvent:event._id ArrayMember:listData];
    
    BookingListController *detail = [[BookingListController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(IBAction)cancelButton:(id)sender
{
    EventListController *detail = [[EventListController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(IBAction)deleteButton:(id)sender
{
    int first = 1;
    NSMutableString * result = [[NSMutableString alloc] init];
    for(int i=0;i<[listData count];i++){
        ParticipateClass *par = [listData objectAtIndex:i];
        if([[keyArray objectForKey:[NSNumber numberWithInt:i ]]integerValue ])
        {
            if(first){
                [result appendString:[NSString stringWithFormat:@"%d",par.userId] ];
                first = 0;
            }else{
                [result appendString:[NSString stringWithFormat:@"-%d",par.userId] ];
            }
        }
    }
    Event *event = [Event instance];
    User *user = [User instance];
    NSString *res = [user deleteMembers:result eventId:event._id userId:user._id];
    if ([res intValue] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Fout"
                                                       message:@"Dat lid is in boeken, kunt u niet verwijderen."
                                                      delegate:nil
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil];
        [alert show];
        [alert release];
    }else{
        BookingListController *detail = [[BookingListController alloc] init];
        [self presentViewController:detail animated:YES completion:NULL];
        [detail release];
    }
}
-(void) showAddMember
{
    EventAddMemberController *detail = [[EventAddMemberController alloc] init];
    if([listNew count]){
        detail.listNew = listNew;
    }else{
        listNew = [[NSMutableArray alloc] init];
        detail.listNew = listNew;
    }
    detail.flagSendPage = YES;
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // Any additional checks to ensure you have the correct textField here.
    [textField resignFirstResponder];
    return YES;
}
@end
